var app = sm("do_App");
var page = sm("do_Page");
var hashdata = mm("do_HashData");
var cartFoot = ui("cartFoot");
var do_Button_order = ui("do_Button_order");
var openHelper = require("helper/open");
var qqmath = require("util/qqmath");
var mallUrl = require("url/mall");
var qqHttp = require("helper/http");
var httpSilence = require("helper/httpSilence");
var listview = ui("do_SlideListView");
var listdata = mm("do_ListData");
var nf = sm("do_Notification");
listview.bindItems(listdata);
var noData = [{"template":3,"labelContent":"购物车还是空的哦"}];
deviceone.checked = "source://image/common/radiocheck.png";
deviceone.unchecked = "source://image/common/radio.png";
var addItems = [];
var total = 0;
var externalDeliverTime = ""
//andriod返回键
page.on("back", function() {
    app.closePage({"cart_main":true});
});

page.on("result", function(data) {
	if(data && data.cart_toOrder && data.product_detail){
		refreshData();
	}
	
});

/* 头部 */
var headerAout = ui("do_ALayout_header");
var addheader = headerAout.add("header", "source://view/reuse/header.ui", 0, 0);
var header = ui("header");
//左上角-返回
var headerLeft = ui(addheader+".headerLeft");
headerLeft.on("touch", function() {
	app.closePage({"cart_main":true});
});

var labelTitle = ui(addheader+".labelTitle");
labelTitle.text = "购物车";

//页面装载 初始化
page.on("loaded", function(){
	refreshData();
});

//删除购物车商品之后刷新
page.on("delete_cart", function() {
	refreshData();
});

function refreshData(){
	//读取当前页面的传入参数
	//var data = page.getData();
	qqHttp.post(mallUrl.url.cart.index, {}, function(data) {
		if(data.externalDeliverTime){
			externalDeliverTime = data.externalDeliverTime;
		}
		listdata.removeAll();//清除数据
		var mapKey = data.externaMapKeys;
		var mapData = data.externaMap;
		if(mapKey.length>0){
			for(var i=0,length=mapKey.length;i<length;i++){
				var ii = mapKey[i];
				var list = mapData[ii];
				listdata.addData([{"template": 2,"name":list[0].supplierName,"note":"（"+externalDeliverTime+"）","checked":"source://image/common/radio.png"}]);
				var datas = [];
				for(var j=0,len=list.length;j<len;j++){
					list[j].checked = "source://image/common/radio.png";
					list[j].template=0;
					list[j].rightTemplate=1;
					datas.push(list[j]);//新的
				}
				listdata.addData(datas);
			}
		}
		if(mapKey.length>0){
			cartFoot.visible = true;
			compute();
		}
		else{
			listdata.addData(noData);
			cartFoot.visible = false;
		}
		listview.refreshItems();//刷新item数据
	});
}

//自定义一个myorder事件，接受从cell传递过来的数据
page.on("myorder", function(d) {
	// 更新第index行的数据
	var index = indexNum(d.id);
	var cell_data = listdata.getOne(index);
	var dataFlag = isSupplier();
	if(dataFlag.length>0&&dataFlag[0]!=d.supplierType||dataFlag.length>0&&dataFlag[0]==1&&dataFlag[1]!=d.supplierId){
		nf.toast("不能订购不同供应商产品。");
		cell_data.checked = deviceone.unchecked;
		listdata.updateOne(index, cell_data);
		listview.refreshItems();
    	return;
	}
	cell_data.checked = d.checked;
	cell_data.quantity = d.quantity;
	var updateCart={}
	updateCart.id = cell_data.id;
	updateCart.quantity = cell_data.quantity;
	updateCart.productId = cell_data.productId;
	httpSilence.post(mallUrl.url.cart.doUpdate,updateCart,function(data){
		if(data && data.error){
			nf.toast(data.error);
			cell_data.quantity = data.stock;
			listdata.updateOne(index, cell_data);
			listview.refreshItems();
	    	return;
		}else{
			// 再更新listdata
			listdata.updateOne(index, cell_data);
			// 重新计算合计和结算数量
			compute();
		}
	});
})
var totalui = ui("totalui");

function compute() {
	var number = 0;
	total = 0;
	addItems = [];
	
	for (var i = 0; i < listdata.getCount(); i++) {
		var cell_data = listdata.getOne(i);
		var checked = cell_data.checked;
		if (checked == deviceone.unchecked) {
			continue;
		} else {
			var quantity = cell_data.quantity*1;
			number = number + quantity;
			var price = cell_data.price * 1;
			total = qqmath.getDight(total+price*quantity,2);  //精确的数字
			var item = {};
			item.productId = cell_data.productSpecId; //商品规格
			item.onlyProductId = cell_data.productId; //商品id
			item.quantity = cell_data.quantity;
			item.img = cell_data.img;
			item.name = cell_data.name;
			item.spec = cell_data.spec;
			item.price = cell_data.price;
			item.marketPrice =cell_data.marketPrice;
			item.supplierId = cell_data.supplierId; //商品供应商ID
			item.supplierType = cell_data.supplierType; //商品供应商类型
			addItems.push(item);
		}
	}
	// 更新ui
	totalui.text = "合计：￥"+total;
	do_Button_order.text = "去结算(" + number + ")";
}
do_Button_order.on("touch",function(){
	//选中的购物车商品，带到结算页面
	if(total <= 0 || addItems.length<1){
		nf.toast("请选择需要购买的商品");
		return;
	}
	for(var i in addItems){
	    if(addItems[0].supplierType != addItems[i].supplierType||addItems[i].supplierType==1&&addItems[0].supplierId !=addItems[i].supplierId){
	    	nf.toast("不能订购不同供应商产品。");
	    	return;
		}
	}
	openHelper.open("source://view/mall/cart/toOrder.ui",{addItems:addItems,total:total});
});

function indexNum(id){
	var alldata = listdata.getRange(0);
	var index = 0;
	for(var i=0,length=alldata.length;i<length;i++){
		if(alldata[i].id==id){
			index = i;
			break;
		}
	}
	return index;
}
/*判断选择中的供应商*/
function isSupplier(){
	var supplierFlag = [];
	for (var i = 0; i < listdata.getCount(); i++) {
		var cell_data = listdata.getOne(i);
		var checked = cell_data.checked;
		if (checked == deviceone.unchecked) {
			continue;
		} else {
			supplierFlag[0] = cell_data.supplierType;
			supplierFlag[1] = cell_data.supplierId;
			break;
		}
	}
	return supplierFlag;
}